package com.lx.boot.web.valid;


import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import lombok.extern.slf4j.Slf4j;

import java.util.function.Function;


@Slf4j
public class CheckValidator implements ConstraintValidator<Check, Object> {

    private Check check;

    private Function<Validate, Boolean> function;

    @Override
    public void initialize(Check check) {
        this.check = check;
        try {
            function = check.function().getConstructor().newInstance();
        } catch (Exception e) {
            log.error("验证参数出现异常,请检查是否实现Function的apply方法,或执行该方法是否抛异常.", e);
            throw new RuntimeException(e);
        }
    }
    @Override
    public boolean isValid(Object para, ConstraintValidatorContext constraintValidatorContext) {
        try {
            return function.apply(new Validate(check.value(), check.ext(),para, constraintValidatorContext));
        } catch (Exception e) {
            log.error("验证参数出现异常,请检查是否实现Function的apply方法,或执行该方法是否抛异常.", e);
            return false;
        }
    }



}